package com.example.supernote.ui.note.components

import android.media.MediaRecorder
import android.os.Environment
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.supernote.R
import com.example.supernote.ui.components.UniformDialog
import com.example.supernote.ui.components.UniformToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException

@Composable
fun AudioRecorder(
    getFilePath: (String?) -> Unit,
    onCancel: () -> Unit,
    fileName: String = "AUDIO_${System.currentTimeMillis()}"
) {
    val context = LocalContext.current
    var mediaRecorder: MediaRecorder? by remember { mutableStateOf(null) }
    var isRecording by remember { mutableStateOf(false) }
    var outputFile by remember { mutableStateOf("") }
    var maxAmplitude by remember { mutableIntStateOf(0) }
    val scope = rememberCoroutineScope()
    val stopRecording: () -> Unit = {
        mediaRecorder?.apply {
            stop()
            release()
        }
        mediaRecorder = null
        isRecording = false
    }
    // toast infos
    val started = stringResource(R.string.note_recorder_started)
    val ended = stringResource(R.string.note_recorder_ended)
    val permissionDeny = stringResource(R.string.permission_deny)

    UniformDialog(
        title = if (isRecording) stringResource(R.string.note_recording) else stringResource(R.string.note_take_audio_before),
        confirmButtonText = if (isRecording) stringResource(R.string.note_recorder_end) else stringResource(R.string.note_recorder_start),
        onCancel = { stopRecording(); onCancel(); getFilePath(null) },
        onConfirm = {
            if (isRecording) {
                stopRecording()
                UniformToast(context, ended)
                getFilePath(outputFile)
                onCancel()
            } else {
                if (ensureDirectoryExists("Audio")) {
                    outputFile = getTargetAbsolutePath("Audio", "$fileName.m4a")
                    mediaRecorder = MediaRecorder().apply {
                        setAudioSource(MediaRecorder.AudioSource.MIC)
                        setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
                        setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
                        setOutputFile(outputFile)
                        try {
                            prepare()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                        start()
                    }
                    isRecording = true
                    UniformToast(context, started)
                    scope.launch(Dispatchers.IO) {
                        while (isRecording) {
                            maxAmplitude = mediaRecorder!!.maxAmplitude
                            delay(100L)
                        }
                    }
                } else {
                    UniformToast(context, permissionDeny)
                }
            }
        },
        body = {
            Row(
                horizontalArrangement = Arrangement.Center,
                verticalAlignment =  Alignment.CenterVertically
            ) {
                Text(stringResource(R.string.note_recorder_voice))
                Spacer(modifier = Modifier.width(5.dp))
                LinearProgressIndicator(
                    progress = { maxAmplitude / 32767f },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(8.dp),
                )
            }
        }
    )
}


fun ensureDirectoryExists(childDirName: String): Boolean {
    val rootDir =
        Environment.getExternalStoragePublicDirectory("${Environment.DIRECTORY_DOWNLOADS}/SuperNote")
    var hasSuccess = true
    if (!rootDir.exists()) {
        hasSuccess = rootDir.mkdirs()
    }
    if (hasSuccess) {
        val targetDir = File("${rootDir.absoluteFile}/$childDirName")
        // 检查目录是否存在，如果不存在则创建
        if (!targetDir.exists()) {
            // 创建目录
            hasSuccess = targetDir.mkdirs()
        }
    }
    return hasSuccess
}

fun getTargetAbsolutePath(childDirName: String, childFileName: String): String =
    Environment.getExternalStoragePublicDirectory("${Environment.DIRECTORY_DOWNLOADS}/SuperNote/$childDirName/$childFileName").absolutePath
